﻿using System;
using System.Text.RegularExpressions;
using NPOI.SS.Util;

namespace Ganss.Excel
{
    /// <summary>
    /// Excel 帮助类
    /// </summary>
    public static class ExcelHelper
    {
        internal static readonly Regex ColumnLetterRegex = new Regex("^$?[A-Z]+$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);

        /// <summary>
        /// Converts Excel column letters to column indexes (e.g. "A" yields 1).
        /// </summary>
        /// <param name="letter">The Excel column letter.</param>
        /// <returns>The column index.</returns>
        public static int LetterToIndex(string letter)
        {
            if (letter == null || !ColumnLetterRegex.IsMatch(letter))
                throw new ArgumentException($"Column letters out of range: {letter}", nameof(letter));
            return CellReference.ConvertColStringToIndex(letter) + 1;
        }

        /// <summary>
        /// Converts a column index to the corresponding Excel column letter or letters (e.g. 1 yields "A").
        /// </summary>
        /// <param name="index">The column index.</param>
        /// <returns>The Excel column letter or letters.</returns>
        public static string IndexToLetter(int index)
        {
            if (index < 1)
                throw new ArgumentException($"Column index out of range: {index}", nameof(index));
            return CellReference.ConvertNumToColString(index - 1);
        }
    }
}